#include <head.h>

void Ls_l(const char *file_name)
{
    struct stat file_stat;
    struct passwd *u_name;
    struct group *g_name;
    stat(file_name, &file_stat);

    // 判定文件类型
    switch (file_stat.st_mode & S_IFMT)
    { // 使用 S_IFMT 掩码获取文件类型
    case S_IFREG:
        printf("-");
        break;
    case S_IFDIR:
        printf("d");
        break;
    case S_IFCHR:
        printf("c");
        break;
    case S_IFBLK:
        printf("b");
        break;
    case S_IFIFO:
        printf("p");
        break;
    case S_IFLNK:
        printf("l");
        break;
    case S_IFSOCK:
        printf("s");
        break;
    default:
        printf("滚");
        break;
    }

    // 文件权限
    printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
    printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
    printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
    printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
    printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
    printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
    printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
    printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
    printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");

     // 链接数
    printf("%2d ", (int)file_stat.st_nlink);

    // 用户名
    u_name = getpwuid(file_stat.st_uid);
    printf("%-7s ", u_name->pw_name);

    // 用户组名
    g_name = getgrgid(file_stat.st_gid);
    printf("%-7s ", g_name->gr_name);

    // 文件大小
    printf("%5d ", (int)file_stat.st_size);

    // 月份和日期
    struct tm *file_tm = gmtime(&file_stat.st_mtime);
    printf("%d月%d ", file_tm->tm_mon + 1, file_tm->tm_mday);

    // 时:分
    printf("%02d:%02d ", file_tm->tm_hour, file_tm->tm_min);

    // 文件名
    printf("%s\n", file_name);
}

void ergodic(const char *dir_name)
{
    // 打开当前目录
    DIR *dir = opendir(dir_name);
    char path[1024]; // 文件路径缓冲区
    if (dir == NULL)
    {
        perror("无法打开目录\n");
        return;
    }
    struct dirent *entry;
    // 读取目录中的每个条目
    while ((entry = readdir(dir)) != NULL)
    {
            // 跳过 "." 和 ".."
            if (entry->d_name[0] == '.' && (entry->d_name[1] == '\0' || (entry->d_name[1] == '.' && entry->d_name[2] == '\0')))
            {
                continue;
            }
            snprintf(path, sizeof(path), "%s/%s", dir_name, entry->d_name);
            Ls_l(path);

        // 如果是目录，递归调用
        if (entry->d_type == DT_DIR)
        {
            // 跳过 "." 和 ".."
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
            {
                ergodic(path);
            }
        }
    }
    // 关闭目录
    closedir(dir);
}
